package m.jclecai.com.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.squareup.okhttp.Request;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import m.jclecai.com.R;
import m.jclecai.com.base.BaseActivity;
import m.jclecai.com.bean.BankBean;
import m.jclecai.com.bean.UserBean;
import m.jclecai.com.constant.Constant_Result;
import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.utils.PreferenceUtil;
import m.jclecai.com.utils.StringUtils;
import m.jclecai.com.utils.http.FastOk;
import m.jclecai.com.utils.http.HttpManager;
import m.jclecai.com.utils.http.responseBody.BaseBody;

/**
 * Created by ZD on 2017/6/3.
 * 提现
 */

public class WithdrawActivity extends BaseActivity {

    UserBean userBean;
    @BindView(R.id.tv_bank)
    TextView tvBank;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_money)
    EditText etMoney;

    @BindView(R.id.tv_allMoney)
    TextView tvAllMoney;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_sure)
    TextView tvSure;
    BankBean bankBean;

    @BindView(R.id.tv_desc_num3)
    TextView mTvDescNum3;

    @Override
    protected int getContentView() {
        return R.layout.activity_withdraw;
    }

    @Override
    protected void initView() {
        super.initView();
        leftOptionText("");
        rightOptionText("切换银行卡");
        setTitle("提现");

//        mTvDescNum3.setText("3.工作日18点前申请提款，当日处理，18点后申请提款，次日处理，到账时间为1~3个银行工作日，若3个工作日后还未到账，请联系客服电话："+PreferenceUtil.readString(this,PreferenceUtil.KF_NUMBER,"")+"。");
    }

    @Override
    protected void initData() {
        super.initData();
        userBean = PreferenceUtil.readUser(this);
        etName.setText(userBean.getRealname());
       // tvAllMoney.setText(userBean.getAllmoney()+"元");
        getCanWithdrawMoney();
    }

    /**
     * http://j5.mycp365.com/withdraw.php?password=63cafa2b020f5f781b03f5756223b5cc&user=kodx1
     * 获取可以提现的金额
     */
    private void getCanWithdrawMoney() {
        showDialog();
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("user",PreferenceUtil.getUserName(this));
        paramsMap.put("password",PreferenceUtil.getPassword(this));

        //HttpManager.postAsString(Constant_Url.WITHDRAW,paramsMap);

        HttpManager.postAsyn(Constant_Url.WITHDRAW, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                dissDialog();
                DisPlay("请检查网络！！！");
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                //这里我们要做的一个操作就是：
                JSONObject jsonObject = JSON.parseObject(response);
                if (jsonObject.get("status").equals("1012")) {
                    tvAllMoney.setText(jsonObject.get("amount").toString());
                }else{
                    DisPlay(jsonObject.get("message").toString());
                }
            }
        },paramsMap);

    }

    @OnClick(R.id.ll_alter_alipay)
    public void onClickAlterAplipay(){

        startActivity(new Intent(this,BindAlipayActivity.class));
        //这里修改或者添加支付宝
     /*   if (TextUtils.isEmpty(userBean.getAlipay())) {
            //这里表示没有添加支付宝；
            startActivity(new Intent(this,BindAlipayActivity.class));

        }else{
            //这里表示跳转；
            startActivityForResult(new Intent(this,BankCardListActivity.class), Constant_Result.CHANGEBANK);
        }*/
    }

    @OnClick(R.id.ll_alter_bink)
    public void onClickAlterBink(){
        //添加或者修改银行卡
        BankBean bankBean = PreferenceUtil.getDefaultWithDrawBank(this);

        if (bankBean == null && userBean != null) {
            //这里表示如果本地没有默认的银行卡的话，使用UserBean中的
            bankBean=userBean.createBankBean();
        }
        if(bankBean==null){
           // startActivity(new Intent(this, BindbankCardActivity.class));

            //这里表示跳转；
            startActivityForResult(new Intent(this,BindbankCardActivity.class), Constant_Result.CHANGEBANK);

        }else{
            //这里表示跳转；
            startActivityForResult(new Intent(this,BankCardListActivity.class), Constant_Result.CHANGEBANK);
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        //这里重新getUserBindInfo的信息；
        getUserInfo();
    }

    private void updateUI() {

        bankBean = PreferenceUtil.getDefaultWithDrawBank(this);
        tvBank.setText("提款银行");
        if (bankBean == null) return;
        tvBank.setText(bankBean.getBank()
                +"(尾号"+ StringUtils.formatBank(bankBean.getBankno())+")");
    }


    void getUserInfo() {
        showDialog();
        String userName = PreferenceUtil.getUserName(this);
        String password = PreferenceUtil.getPassword(this);
        HashMap<String, String> pair = new HashMap<>();
        pair.put("user", userName);
        pair.put("password", password);

        HttpManager.postAsyn(Constant_Url.GET_USER_INFO, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                dissDialog();

            }

            @Override
            public void onResponse(String response) {

                dissDialog();
                UserBean usb = FastOk.get(response, UserBean.class);
                if (usb == null || "1011".equals(usb.getStatus()) ) {
                    DisPlay(setString(R.string.error_network));
                    return;
                }
                userBean = usb;

                PreferenceUtil.writeUser(WithdrawActivity.this, userBean);
                updateUI();
            }
        }, pair);
    }

    @Override
    protected void resetWindow() {
    }

    @OnClick(R.id.tv_sure)
    void withDraw(){
        String money = etMoney.getText().toString();
        if(bankBean == null){
            DisPlay("请选择要提现的银行卡");
            return;
        }
        if(TextUtils.isEmpty(money)){
            DisPlay("请输入提款金额");
            return;
        }
        if(Float.parseFloat(money) > Float.parseFloat(userBean.getAllmoney())){
            DisPlay("最多可提款"+userBean.getAllmoney()+"元");
            return;
        }
        if(Float.parseFloat(money) < 10){
            DisPlay("最少提款10元");
            return;
        }

        showDialog();
        Map<String,String> pair = new HashMap<>();
        pair.put("user", PreferenceUtil.getUserName(this));
        pair.put("money", money);
        pair.put("password", PreferenceUtil.getPassword(this));
        pair.put("bankid", bankBean.getId());

        HttpManager.postAsyn(Constant_Url.WITHDRAW, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                dissDialog();
                DisPlay(getString(R.string.error_network));
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                BaseBody baseBody = FastOk.get(response, BaseBody.class);
                if(baseBody != null) {
                    DisPlay(baseBody.getMessage());
                    if(baseBody.getStatus() == 0)
                        finish();
                }else {
                    DisPlay(getString(R.string.error_network));
                }
            }
        },pair);
    }

    @OnClick(R.id.tv_time)
    void time(){
        Intent intent = new Intent(this, WebHelperActivity.class);
        intent.putExtra("title", "提款到账时间");
        intent.putExtra("code", Constant_Url.WITHDRAWTIME);
        startActivity(intent);
    }

    @OnClick(R.id.tv_right_option)
    void changeBankCard(){
        startActivityForResult(new Intent(this,BankCardListActivity.class), Constant_Result.CHANGEBANK);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
       /* if(resultCode == RESULT_OK){
            onResume();
        }*/
    }


}
